from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from . import constants
from django.http import HttpResponse
from rest_framework.generics import GenericAPIView
from .serializers import RegisterSMSCodeSerializer
from random import randint
from libs.yuntongxun.sms import CCP
# Create your views here.

class RegisterImageCodeView(APIView):

    """
    实现图片验证码

    GET              /verifications/imagecodes/(?P<image_code_id>.+)/

    """
    def get(self,request,image_code_id):
        # 1.生成图片和验证码
        text,image = captcha.generate_captcha()
        # 2.需要把验证码保存到redis
        # 连接redis
        redis_conn = get_redis_connection('code')
        # text
        redis_conn.setex('img_%s'%image_code_id,constants.IMAGE_CODE_EXPIRE_TIME,text)

        #content_type = mime
        # text/html image/jpeg image/png

        return HttpResponse(image,content_type='image/jpeg')

class RegisterSMSCodeView(GenericAPIView):

    """
    获取短息验证码

     GET            /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx
    1. 需要将用户提交的图片验证码 发送给我们，供我们校验
    2. 校验成功 ，发送短信验证码
    3.需要对短信进行记录
    4.记录发送的标记

    """

    serializer_class = RegisterSMSCodeSerializer

    def get(self,request,mobile):

        # 1.获取用户提交的数据 进行校验
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 2.生成短信
        sms_code = '%06d'%randint(0,999999)
        # 3.记录
        redis_conn = get_redis_connection('code')
        redis_conn.setex('sms_%s'%mobile,5*60,sms_code)

        # 4.发送
        # ccp = CCP()
        #
        # ccp.send_template_sms(mobile,[sms_code, 5],1)

        from celery_tasks.sms.tasks import send_sms_code

        # 函数必须采用函数名.delay（）参数就放到delay中
        send_sms_code.delay(mobile,sms_code)

        return Response({'message':'ok'})

